/*
 * @Author: liaoxin
 * @email: 2858765077@qq.com
 * @FilePath: \personnelmanage\src\lib\ui\UdFormControls\UdMonthRangePicker\UdMonthRangePicker.tsx
 * @Date: 2022-09-07 10:02:00
 * @LastEditTime: 2022-09-14 09:35:48
 */
import React, { PureComponent } from 'react'
import { DatePicker, message } from 'antd'
import { IUdFormItem, Modify } from '../../..'
import moment from 'moment'
import 'moment/locale/zh-cn.js'
import { RangePickerValue, RangePickerProps } from 'antd/lib/date-picker/interface'

moment.locale('zh-cn')

const { RangePicker } = DatePicker
class UdMonthRangePicker extends PureComponent<IUdDateRangePickerProps, IUdDateRangePickerState> {

  constructor(props: IUdDateRangePickerProps) {
    super(props);
    this.state = {
      values: [],
      open: false
    }
  }

  componentDidMount() {
    this.handleProps(this.props)
  }

  componentWillReceiveProps(nextProps: Readonly<IUdDateRangePickerProps>) {
    this.handleProps(nextProps)
  }

  render() {
    let values: any = {}
    if (this.state.values && this.state.values.length > 0) {
      values.value = this.state.values
    }
    return (
      <RangePicker
        className="ud-range-picker"
        format="YYYY-MM"
        mode={['month', 'month']}
        placeholder={['开始月份', '结束月份']}
        {...this.props}
        {...values}
        allowClear={false}
        open={this.state.open}
        onOpenChange={this.handleOpenChange}
        onPanelChange={(value, mode) => this.handlePanelChange(value, mode)} />
    )
  }

  private handleProps = (props: IUdDateRangePickerProps) => {
    if (props.value && (props.value[0] || props.value[1])) {
      this.setState({ values: [moment(props.value[0]), props.value[1] ? moment(props.value[1]) : ''] })
    } else {
      const formatDate = [moment().format('YYYY-MM'), moment().format('YYYY-MM')]
      this.props.onChange!(formatDate)
      this.setState({ values: [moment(), moment()] })
    }
  }

  handlePanelChange = (value: RangePickerValue, mode: string | moment.MomentInput[]) => {
    this.setState({ values: value });
    if (Number(moment(value[1]).format('X')) - Number(moment(value[0]).format('X')) > 15552000) {
      message.warning('统计月份区间要在六个月之内')
      return
    }
    if (mode[1] === 'date') {
      const formatDate = [moment(value[0]).format('YYYY-MM'), moment(value[1]).format('YYYY-MM')]
      this.props.onChange!(formatDate)
      this.setState({ open: false });
    }
  }

  handleOpenChange = (open: boolean) => {
    this.setState({ open: open })
  }
}

interface IUdDateRangePickerProps extends Partial<IUdFormItem>, Modify<RangePickerProps, {
  id?: string | string[]
}> {
  value?: any
  onChange?(value: any): void
  valueFormat?: string[]
}

interface IUdDateRangePickerState {
  values?: any
  open?: boolean
}
export default UdMonthRangePicker